package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.merchant.common.PcCouponCustomer;
import cc.linker.steplink.crm.merchant.dao.CouponPcDao;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.pojo.ShopGoods;
import cc.linker.steplink.crm.merchant.pojo.Sku;
import cc.linker.steplink.crm.merchant.pojo.coupon.SendCouponDto;
import cc.linker.steplink.crm.merchant.util.Global;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.service.coupon.CouponH5Service;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class CouponPcService {

    @Autowired
    private CouponPcDao couponPcDao;

    @Autowired
    private IsLossGoodsService isLossGoodsService;
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private NewMallService newMallService;
    @Autowired
    private PcCouponCustomer pcCouponCustomer;
    @Autowired
    private CouponRequest couponRequest;

    @Autowired
    private MallBoomDao mallBoomDao;

    @Autowired
    private CouponH5Service couponH5Service;

    /**
    * @Description：系统给用户发券
    * @DateTime：2020/12/11 15:47
    * @Params：
    * @Return：
    */
    public void sendCoupon(SendCouponDto sendInfo, HttpServletRequest request) {
        LOGGER.info("系统后台给指定用户进行发券操作------------------" + JSON.toJSONString(sendInfo));
        if (StringUtils.isEmpty(sendInfo.getCouponId())) {
            throw GlobalException.build("请输入卡券ID");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("couponId", sendInfo.getCouponId());
        Map<String, Object> couponInfo = this.getInfo(param, request);
        if (couponInfo == null) {
            throw GlobalException.build("卡券未找到");
        }
        if (sendInfo.getCustomerIds() != null && sendInfo.getCustomerIds().size() > 0) {
            for (String customerId : sendInfo.getCustomerIds()) {
                Map<String, Object> customerInfo = this.mallBoomDao.getCustomerInfoByCustomerId(customerId);
                if (customerInfo != null) {
                    CouponCustomerInfo h5CustomerInfo = CouponCustomerInfo
                            .builder()
                            .customerId(customerId)
                            .customerName(customerInfo.containsKey("wxName") && customerInfo.get("wxName") != null ? customerInfo.get("wxName").toString() : "")
                            .customerPhone(customerInfo.containsKey("bindPhone") && customerInfo.get("bindPhone") != null ? customerInfo.get("bindPhone").toString() : "")
                            .cover("")
                            .orgId((String) customerInfo.get("orgId"))
                            .sourceUserId("")
                            .build();
                    Map<String, Object> receiveParam = new HashMap();
                    Map<String, Object> reMap = new HashMap<>();
                    reMap.put("couponId", sendInfo.getCouponId());
                    reMap.put("publishId", "");
                    reMap.put("num", 0);
                    List<Map<String, Object>> coupons = new ArrayList<>();
                    coupons.add(reMap);
                    receiveParam.put("isActivity", false);
                    receiveParam.put("couponList", coupons);
                    this.couponH5Service.receiveConsumption(receiveParam, h5CustomerInfo, false);
                }
            }
        }
    }

    public void addCouponGoodsData(Map<String, Object> param) throws ParseException {
        String goodsType = param.get("goodsType").toString();
        //全部商品
        List<Integer> gIdList = new ArrayList<>();
        if("0".equals(goodsType)){
            gIdList.add(0);
        }
        if("3".equals(goodsType)){
            gIdList.add(-1);
        }
        //可用商品 //不可用商品
        if("1".equals(goodsType) || "2".equals(goodsType)){
            gIdList = (List)param.get("goodsIds");
        }
        if(gIdList.size()>0){
            List<Map<String,Object>> daList = new ArrayList<>();
            for (Integer gid:gIdList) {
                Map<String,Object> da = new HashMap<>();
                da.put("goodsId",gid);
                da.put("couponId",param.get("couponId"));
                da.put("goodsType",param.get("goodsType"));
                da.put("beLongId",param.get("beLongId"));
                da.put("orgId",param.get("orgId"));
                da.put("couponEndTime","0000-00-00 00:00:00");
                if(!StringUtils.isEmpty(param.get("endTime"))){
                    da.put("couponEndTime",param.get("endTime"));
                }else{
                    int validDays = Integer.valueOf(param.get("validDays").toString());
                    String publishEndTime = param.get("publishEndTime").toString();
                    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(publishEndTime);
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(date);
                    if(!StringUtils.isEmpty(param.get("useTimeType")) && "1".equals(param.get("useTimeType").toString())){
                        calendar.add(Calendar.DATE,validDays-1);//把日期往后增加一天.整数往后推,负数往前移动
                        date = calendar.getTime();
                        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                        String datetime = dateStr.format(date);
                        da.put("couponEndTime",datetime);
                    }
                    if(!StringUtils.isEmpty(param.get("useTimeType")) && "2".equals(param.get("useTimeType").toString())){
                        calendar.add(Calendar.DATE,validDays);//把日期往后增加一天.整数往后推,负数往前移动
                        date = calendar.getTime();
                        SimpleDateFormat dateStr = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                        String datetime = dateStr.format(date);
                        da.put("couponEndTime",datetime);
                    }
                }
                da.put("customerCouponNumCrm",param.get("customerCouponNumCrm"));
                da.put("customerTypeCrm",param.get("customerTypeCrm"));
                da.put("groupIdCrm",param.get("groupIdCrm"));
                daList.add(da);
            }
            couponPcDao.addCouponGoodsData(daList);
        }else{
            throw GlobalException.build("参数错误");
        }
    }

    public Map<String,Object> getCouponGoodsData(String couponId){
        return couponPcDao.getCouponGoodsData(couponId);
    }

    public void saveCouponGoodsData(Map param) throws ParseException {
        couponPcDao.delCouponGoodsData(param);
        addCouponGoodsData(param);
    }

    public List<Map<String, Object>> getGoodsList(String goodsIds,Integer sale,String orgId) {
        return couponPcDao.getGoodsList(goodsIds,sale,orgId);
    }

    public List<String> getCouponIdByGoodsId(String goodsId) {
        return couponPcDao.getCouponIdByGoodsId(goodsId);
    }


    /**
     * @Description: 创建或编辑优惠券判断亏损
     * @Param: [couponInfo 优惠券详情]
     * @Return: java.util.Map
     * @Author: ch
     * @Date: 2020/8/29 13:20
     * @Version:
     **/
    public void isLossCoupon(Map couponInfo, String orgId){
        Integer goodsType = 0;
//        List<Long> goodsIds =null;
        if(!StringUtils.isEmpty(couponInfo.get("goodsType"))){
            goodsType = Integer.valueOf(couponInfo.get("goodsType").toString());
        }
        String goodsIdsString ="";
        if(!StringUtils.isEmpty(couponInfo.get("goodsIds"))){
            goodsIdsString = couponInfo.get("goodsIds").toString();
        }
        Map surchMap = new HashMap();
        surchMap.put("goodsType",goodsType);
        surchMap.put("goodsIds",goodsIdsString);
        surchMap.put("orgId",orgId);
        surchMap.put("sale",couponInfo.get("sale"));
        surchMap.put("customerId",couponInfo.get("customerId"));
        //获取商品列表
        List<ShopGoods> goodsList = this.getGoods(surchMap);
        if(goodsList!=null && goodsList.size()>0){
            for(ShopGoods goods : goodsList){
                Map goodsMap = BeanMapUtils.beanToMap(goods);
                goodsMap = isLossGoodsService.reduceGoodsInfoByMap(goodsMap,couponInfo);
                //判断亏损
                newMallService.checkGoodsRewetting(goodsMap);
            }
        }
    }

    public List<ShopGoods> getGoods(Map map) throws GlobalException {
        List<ShopGoods> shopGoodsList = shopGoodsMapper.getGoodsListByCoupon(map);
        if(shopGoodsList!=null && shopGoodsList.size()>0){
            for ( ShopGoods shopGoods : shopGoodsList){
                List<Sku> sku = shopGoodsMapper.getSkuByGoodsId(shopGoods.getGoodsId());
                shopGoods.setSku(sku);
                // 如果启用了运费模板 设置运费值为模板运费最低值
                if((null==shopGoods.getIsFreeFreight() || 0==shopGoods.getIsFreeFreight()) && !StringUtils.isEmpty(shopGoods.getFreightTemplateId())){
                    shopGoods.setGoodsFreight(Double.valueOf(maiBaoLaDao.getLeastTemplateFee(shopGoods.getFreightTemplateId())));
                    shopGoods.setFreightTemplateName(maiBaoLaDao.getFreightTemplateNameById(shopGoods.getFreightTemplateId()));
                }
            }
        }

        return shopGoodsList;
    }

    public Map<String,Object> getInfo(Map<String, Object> param, HttpServletRequest request) {
        return (Map)couponRequest.doRequest("coupon-detail", param, pcCouponCustomer.getCouponCustomerInfo(request));
    }

    public List<String> getCouponIdByCustomerType(Map<String, Object> customerTypeParam) {
        return couponPcDao.getCouponIdByCustomerType(customerTypeParam);
    }

    public List<String> getSalerId(String orgId) {
        return couponPcDao.getSalerId(orgId);
    }
}
